package com.example.demo.advice;


import com.example.demo.bean.APIResponseBean;
import com.example.demo.bean.APIResponseBeanUtil;
import com.example.demo.enums.APIErrorCommonEnum;
import com.example.demo.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<APIResponseBean> exceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        APIResponseBean apiResponseBean = null;
        if (e instanceof BusinessException) {
            apiResponseBean =  APIResponseBeanUtil.error(((BusinessException) e).getCode(), e.getMessage());
        }
        if (e instanceof IllegalArgumentException) {
            apiResponseBean =  APIResponseBeanUtil.error(500, e.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            apiResponseBean =  APIResponseBeanUtil.error(APIErrorCommonEnum.VALID_EXCEPTION.getCode(), APIErrorCommonEnum.VALID_EXCEPTION.getMessage());
        }

        return new ResponseEntity(apiResponseBean, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
